<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简易聊天系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }

        label {
            display: inline-block;
            width: 100px;
            margin-right: 10px;
            text-align: right;
        }

        input {
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }

        button {
            padding: 5px 10px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        #messages {
            border: 1px solid #ccc;
            padding: 10px;
            background-color: white;
            min-height: 200px;
            overflow-y: auto;
        }

       .message {
            margin-bottom: 10px;
            padding: 5px 10px;
            border-radius: 5px;
        }

       .message:nth-child(odd) {
            background-color: #e9ecef;
        }

       .input-row {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        #msgInput {
            width: 300px; /* 增大消息输入框宽度 */
        }
    </style>
</head>

<body>
    <div class="input-row">
        <label for="name">登录用户名：</label>
        <input type="text" id="name">
        <label for="hyname">好友名称：</label>
        <input type="text" id="hyname">
        <button onclick="connect()">确认聊天</button>
    </div>
    <div class="input-row">
        <input type="text" id="msgInput">
        <button onclick="send()">发送</button>
    </div>
    <div id="messages"></div>

    <script>
        let ws;

        // 建立连接
        function connect() {
            const name = document.getElementById("name").value;
            const hyname = document.getElementById("hyname").value;
            if (!name ||!hyname) {
                alert("请输入用户名和好友名称");
                return;
            }
            ws = new WebSocket(`ws://localhost:8080/chat/${name}/${hyname}`);

            ws.onopen = () => {
                // 建立连接时查询聊天记录
                fetchChatHistory();
            };

            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                console.log(data);
                // 收到消息时查询聊天记录
                fetchChatHistory();
            };

            ws.onclose = () => {
                console.log('WebSocket连接已关闭');
            };
        }

        // 查询聊天记录
        function fetchChatHistory() {
            const name = document.getElementById("name").value;
            const hyname = document.getElementById("hyname").value;
            fetch(`http://localhost:8080/user/getall/${name}/${hyname}`)
               .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
               .then(data => {
                    if (!data ||!data.data ||!Array.isArray(data.data)) {
                        console.error('后端返回数据格式不正确');
                        return;
                    }
                    const messagesDiv = document.getElementById("messages");
                    messagesDiv.innerHTML = "";
                    data.data.forEach(item => {
                        if (item && typeof item.fromid === 'number' && typeof item.toid === 'number' && typeof item.msg ==='string') {
                            const msgElement = document.createElement("div");
                            msgElement.classList.add('message');
                            msgElement.textContent = ` ${item.msg}`;
                            messagesDiv.appendChild(msgElement);
                        } else {
                            console.error('聊天记录数据项格式不正确', item);
                        }
                    });
                })
               .catch(error => {
                    console.error('获取聊天记录时出错:', error);
                });
        }

        // 发送消息
        function send() {
            if (!ws) {
                alert("WebSocket连接未初始化，请先建立连接");
                return;
            }
            if (ws.readyState!== WebSocket.OPEN) {
                alert("WebSocket连接未就绪，请稍候再试");
                return;
            }
            const msg = document.getElementById("msgInput").value;
            if (!msg) {
                return;
            }
            const name = document.getElementById("name").value;
            const hyname = document.getElementById("hyname").value;
            ws.send(JSON.stringify({
                hyname: hyname,
                name: name,
                msg: msg
            }));
            document.getElementById("msgInput").value = ""; // 清空输入框

            // 发送消息时，同时发送一个HTTP请求
            const msgData = {
                hyname: hyname,
                name: name,
                msg: msg
            };
            fetch('http://localhost:8080/user/addmsg', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(msgData)
            })
           .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
           .then(data => {
                console.log('HTTP请求响应:', data);
            })
           .catch(error => {
                console.error('发送HTTP请求时出错:', error);
            });

            // 发送消息后查询聊天记录
            fetchChatHistory();
        }
    </script>
</body>

</html>